//加载必须的模块
var http = require('http')
var fs = require('fs')
var url = require('url')
var path = require('path')

//创建服务器
var server = http.createServer(function(req, res) {

        var pathObj = url.parse(req.url, true)

        if (pathObj.pathname === '/') {
            pathObj.pathname = './index.html'
        }

        // 处理API请求
        if (pathObj.pathname.includes('/api')) {
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.writeHead(200, { "Content-Type": "application/json" });
            var otherObject = [{ item1: "item1val", item2: "item2val" }, { item1: "item1val", item2: "item2val" }]
            var json = JSON.stringify(otherObject);
            res.end(json)
        } else {
            // 处理静态文件访问

            //读取静态目录里面的文件，然后发送出去
            var filePath = path.join(path.join(__dirname, '/'), pathObj.pathname)
            console.log(filePath);
            fs.readFile(filePath, 'binary', function(err, content) {
                if (err) {
                    res.writeHead(404, 'Not Found')
                    res.end('<h1>404 Not Found</h1>')
                } else {
                    res.writeHead(200, 'Not Found')
                    res.write(content, 'binary')
                    res.end()
                }
            })
        }
    })
    //监听8080端口
server.listen(8080)
console.log('http://localhost:8080')